package com.example.demo1.web;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.demo1.JsonParse;
import com.example.demo1.MainActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Request;

public class Web {
    public static RequestQueue queue;
    public static Request request;
    protected static final int CHANGE_UI = 1;
    protected static final int ERROR = 2;

    public  Web (Context context){
        this.queue=Volley.newRequestQueue(context);
    }

    MHandler mHandler=new MHandler();
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == CHANGE_UI) {
                String str=(String) msg.obj;
                System.out.println("输出+"+str);

            } else if (msg.what == ERROR) {
            }
        }

        ;
    };




    public String getJson(){

        new Thread() {
            public void run() {

                try {
                    URL url = new URL("http://rap2api.taobao.org/app/mock/284025/login");  //创建URL对象
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    // 设置请求的方式
                    conn.setRequestMethod("GET");
                    //设置超时时间
                    conn.setConnectTimeout(5000);
                    Log.i("log", "123");
                    int code = conn.getResponseCode();
                    System.out.println(code);
                    Log.i("log", code + "");
                    if (code == 200) {
                        InputStream is = conn.getInputStream();


                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                                    byte[] data = new byte[1024];
                                    int len = 0;
                                    InputStream inStream = conn.getInputStream();
                                                     while ((len = inStream.read(data)) != -1) {
                                                             outStream.write(data, 0, len);
                                                         }
                                                     inStream.close();
                                                     String msgJson=new String(outStream.toByteArray());
                                    System.out.println("数据："+msgJson);

                        Message msg = new Message();
                        msg.what = CHANGE_UI;
                        msg.obj = msgJson;
                        handler.sendMessage(msg);



                    } else {


                    }
                } catch (Exception e) {

                }
            }


        }.start();

    return "";
    }







    class MHandler extends Handler {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.obj != null) {
                String vlResult = (String) msg.obj;
                Log.i("TAG", vlResult);
                System.out.println("结果"+vlResult);
                //解析获取的JSON数据
                //newsInfos = JsonParse.getNewsInfo(vlResult);
                //lvNews.setAdapter(new NewsAdapter());
            }
        }
    }




    /**
     2      * 从指定的URL中获取数组
     3      * @param urlPath
     4      * @return
     5      * @throws Exception
     6      */
     public  String readParse(String urlPath) throws Exception {
         System.out.println("执行readParse");
                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        byte[] data = new byte[1024];
                         int len = 0;
                         URL url = new URL(urlPath);
                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                         InputStream inStream = conn.getInputStream();
                         while ((len = inStream.read(data)) != -1) {
                             outStream.write(data, 0, len);
                         }
                         inStream.close();
         System.out.println("数据"+new String(outStream.toByteArray()));
                         return new String(outStream.toByteArray());//通过out.Stream.toByteArray获取到写的数据
                     }



    //getNews(); //OKhttp访问网络

    //使用Volley访问网络
    public void getnewsDatas() {
        System.out.println("执行web");
        //String url="http://172.21.145.201:8080/NewsInfo.json";
        String url="http://rap2api.taobao.org/app/mock/284025/login";//主机的IP

        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                String json = jsonArray.toString();
               // newsInfos = JsonParse.getNewsInfo(json);
                //if (newsInfos == null) {
                //   Toast.makeText(MainActivity.this, "解析失败", Toast.LENGTH_SHORT).show();
               // } else {
                    //更新界面
                    // loading.setVisibility(View.INVISIBLE);
                    //lvNews.setAdapter(new NewsAdapter());
               // }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
                JSONArray jsonArray;
                try {
                    jsonArray = new JSONArray(new String(response.data, "UTF-8"));
                    return Response.success(jsonArray, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return Response.error(new ParseError(e));
                } catch (JSONException e) {
                    e.printStackTrace();
                    return Response.error(new ParseError(e));
                }
            }
        };
        queue.add(jsonArrayRequest);
    }

}
